from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import Email, EqualTo, InputRequired, ValidationError
from app.models import User


class BaseForm(FlaskForm):
    def get_error(self):
        message = self.errors.popitem()[1][0]
        return message


class LoginForm(BaseForm):
    email = StringField(validators=[Email(), InputRequired()])  # 邮箱
    password = StringField(validators=[InputRequired()])  # 密码
    switch = StringField(validators=[])

    def validate(self):
        check_validate = super(LoginForm, self).validate()
        # 如果验证未通过
        if not check_validate:
            return False
        # 检测用户是否存在
        user = User.query.filter_by(email=self.email.data).first()
        if not user:
            self.email.errors.append('该邮箱用户不存在')
            return False

        # 检测密码与邮箱是否匹配
        if not user.check_password(self.password.data):
            self.password.errors.append('密码错误')
            return False
        if not user.enabled:
            self.email.errors.append('该用户暂未激活，请联系管理员进行授权！')
            return False
        return True


class RegistForm(BaseForm):
    email = StringField(validators=[Email(), InputRequired()])  # 邮箱
    username = StringField(validators=[InputRequired()])  # 用户昵称
    password = StringField(validators=[InputRequired()])  # 密码

    def validate(self):
        check_validate = super(RegistForm, self).validate()
        # 如果验证未通过
        if not check_validate:
            return False
        # 检测用户是否存在
        user = User.query.filter_by(email=self.email.data).first()
        if user:
            self.email.errors.append('该邮箱已存在')
            return False
        return True
